/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.core.handler;

import static com.chinamobile.cmss.lakehouse.common.kubernetes.K8sModelConstant.CLUSTER_NAMESPACE_PREFIX;
import static com.chinamobile.cmss.lakehouse.common.kubernetes.K8sModelConstant.NAMESPACE_SEPARATOR;

public class K8sServiceHandler {

    public static final String SERVICE_SEPARATOR = ".";
    public static final String PORT_SEPARATOR = ":";

    private static String k8sClusterDomain = ".svc.cluster.local";

    public static String componentDomainService(String namespace, String serviceName) {
        return serviceName + SERVICE_SEPARATOR + namespace + k8sClusterDomain;
    }

    public static String clusterNamespace(String clusterName) {
        return CLUSTER_NAMESPACE_PREFIX + NAMESPACE_SEPARATOR + clusterName.replace("_", "-");
    }

    /**
     * <svc>.<namespace>.<k8s.domain>:<port>
     */
    public static String componentDomainService(String namespace, String serviceName,
                                                int servicePort) {
        return serviceName + SERVICE_SEPARATOR + namespace + k8sClusterDomain + PORT_SEPARATOR
            + servicePort;
    }

    /**
     * <svc-0>.<namespace>.<k8s.domain>:<port>,<svc-1>.<namespace>.<k8s.domain>:<port>
     */
    public static String componentServicesString(String namespace, String serviceName,
                                                 int servicePort, int replica) {

        StringBuilder svc = new StringBuilder();

        for (int i = 0; i < replica; i++) {
            svc.append(serviceName).append("-").append(i);
            svc.append(".");
            svc.append(namespace);
            svc.append(k8sClusterDomain);
            svc.append(PORT_SEPARATOR);
            svc.append(servicePort);
            svc.append(",");
        }

        // delete last ','
        svc.deleteCharAt(svc.length() - 1);

        return svc.toString();
    }

}
